import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<WebState> buildEffect() {
  return combineEffects(<Object, Effect<WebState>>{
    WebAction.onInit: _onInit,
    WebAction.onDone: _onDone,
    WebAction.onShare: _onShare,
  });
}

void _onInit(Action action, Context<WebState> ctx) {
  _startCountupTimer(ctx, 100);
}

void _onDone(Action action, Context<WebState> ctx) {
  Navigator.of(ctx.context).pop(ctx.state.done);
}

void _onShare(Action action, Context<WebState> ctx) async {
  final String select = await Util.showShareDialog(ctx.context);

  if (select == 'session') {
    fluwx.share(fluwx.WeChatShareWebPageModel(
        title: "title", // todo
        description: "desc",
        scene: fluwx.WeChatScene.SESSION,
        webPage: "https://baidu.com",
        thumbnail: ""));
  } else if (select == 'timeline') {
    fluwx.share(fluwx.WeChatShareWebPageModel(
        title: "title", // todo
        description: "desc",
        scene: fluwx.WeChatScene.TIMELINE,
        webPage: "https://baidu.com",
        thumbnail: ""));
  }
}

Timer _timer;
var _counter = 0;

void _startCountupTimer(Context<WebState> ctx, max) {
  const oneSec = const Duration(seconds: 1);

  var callback = (timer) {
    if (ctx.isDisposed) {
      _timer.cancel();
      return;
    }

    ctx.dispatch(WebActionCreator.countUp(_counter));
    if (_counter == max) {
      _timer.cancel();
    } else {
      _counter += 1;
    }
  };

  _counter = 1;
  ctx.dispatch(WebActionCreator.countUp(_counter));
  _counter += 1;

  _timer = Timer.periodic(oneSec, callback);
}

//void _cancelTimer(Context<WebState> ctx) {
//  _timer.cancel();
//  _counter = 0;
//  ctx.dispatch(WebActionCreator.onCountUp(0));
//}
